class TasksController < ApplicationController
before_filter :require_any_user

  def index
    if current_user.role_id==1
      @tasks = Task.find(:all)
    else
      tasks = Task.find(:all)
      @tasks= []

      #Add all the Taks where the owner project is the current user (Readeable and Editable)
      tasks.each do |thisTask|
        if thisTask.project.user_id==current_user.id || (thisTask.user_id==current_user.id && thisTask.project_id!=1 && current_user.role_id==3)
          @tasks << thisTask
        end
      end

    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @tasks }
    end
  end

  def show
    @monday=Date.today.monday
    @task = Task.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @task }
    end
  end

  def new
    @task = Task.new
    @task.percentage=0

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @task }
    end
  end

  def edit
    @task = Task.find(params[:id])
  end

  def create
    @task = Task.new(params[:task])
      unless params['commit']=="Guardar"
        redirect_to( :controller => 'tasks' )
        return false
      end

    respond_to do |format|
      if @task.save
        format.html { redirect_to(@task, :notice => 'Tarea creada de forma satisfactoria.') }
        format.xml  { render :xml => @task, :status => :created, :location => @task }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
      unless params['commit']=="Guardar"
        redirect_to( :controller => 'tasks' )
        return false
      end
    @task = Task.find(params[:id])

    respond_to do |format|
      if @task.update_attributes(params[:task])
        format.html { redirect_to(@task, :notice => 'Tarea actualizada de forma satisfactoria.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @task.errors, :status => :unprocessable_entity }
      end
    end
  end

  def destroy
    @task = Task.find(params[:id])

      @task.week_time_sheets.each{ |x|
        x.destroy
      }
    @task.destroy

    respond_to do |format|
      format.html { redirect_to(tasks_url) }
      format.xml  { head :ok }
    end
  end

  def update_date

  end
end
